package com.demo.gateway.timer;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.demo.gateway.pojo.GatewayRouteDO;
import com.demo.gateway.service.impl.DatabaseRouteServcie;
import com.demo.gateway.service.impl.DynamicGatewayRouteServcie;
import com.demo.gateway.service.impl.RedisRouteService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author: demo
 * @date: 2020年6月28日
 * @Document : 同步数据定时器
 */
@SuppressWarnings("unused")
@Slf4j
@Component("syncDataTimer")
public class SyncDataTimer {
	@Autowired
	private RedisRouteService redisRouteService;

	@Autowired
	private DatabaseRouteServcie databaseRouteServcie;

	@Autowired
	private DynamicGatewayRouteServcie dynamicGatewayRouteServcie;

	/**
	 * 定时检查redis数据丢失时,从数据库同步
	 * 使用quartz 动态在库里设置定时时间
	 * //	@Scheduled(cron = "0 0/1 * * * ? ")
	 */
	public void database2Redis() {
		try {
			List<GatewayRouteDO> routeBeans = redisRouteService.queryRedisRoutes();
			if (routeBeans == null||routeBeans.size()==0) {
				routeBeans = databaseRouteServcie.queryDatabaseRoutes();
				if (routeBeans != null&&routeBeans.size()>0) {
					redisRouteService.addRedisRoutes(routeBeans);
					dynamicGatewayRouteServcie.refreshRoute();
					log.debug("同步数据库路由信息至redis成功!");
				} else {
					log.warn("<==未获取到网关路由信息==>");
				}
			}else {
				log.debug("check redis routes success ...");
			}
		} catch (Exception e) {
			log.error("同步路由信息异常!!!", e);
		}
	}
}
